<?php
namespace Utuo; 

/**
 * 客户购物车
 * @author song
 */
class DisCart {
	
	// 用户id
	private $uid;

	// 客户id
	private $cid;

	// 商品列表
	private $items = array(
// 			'商品id' => array(
// 					'productId(商品id)' => 1,
// 					'name(商品名称)' => '',
// 					'support_cod' => 0,
// 					'items(购买项)'  => array(
// 						'businessId(购物车中的记录id)' = array(
// 									'businessId(购物车中的记录id)' => 5,
// 									'productPrice(商品拍下价格)' => 8.90,
// 									'quantity(商品购买数量)' => 3,
// 									'pic(商品的图片)' => "http://...."
// 									'attrs(商品的属性)' => array(
// 										 "属性名" => "属性值",
// 									     //... ...
// 									 ),
// 						   ),
// 						),
// 					),
// 			//... ...
	);
	
	private $config = array(
		'new_data' => true,
	);
	
	/**
	 * 获得购物车
	 * @param int $uid 登录的用户id
	 * @param int $sid 商户 id
	 * @return Ambigous <\Utuo\Cart, mixed, NULL>
	 */
	public final static function getCart($uid, $sid) {
		static $cart = null;
		if(!$cart) { // 无购物车
			$cart = new \Utuo\DisCart($uid, $sid);
		}
		return $cart;
	}

	// 商品数量
	public function getCount() {
		$count = 0;
		foreach ($this->items as $k => $v) {
			foreach ($v['items'] as $v1) {
				$count+=$v1['quantity'];
			}
		}
		return $count;
	}

	// 获得销售客户id
	public function getCid() {
		return $this->cid;
	}
	
	// 获得用户id
	public function getUid() {
		return $this->uid;
	}

	// 设置用户id
	public function setUid($uid) {
		$this->uid = $uid;
	}
	
	// 获得所有商品
	public function getItems() {
		return $this->items;
	}

	public function __construct($uid, $cid) {
		$this->setUid($uid);
		$this->cid = $cid;
		$this->_init();
	}

	// 初始化
	private function _init() {
		$d = D("DistributionShopCart");
		$cartItems = array();
		$items = $d->where("cid=%d and uid=%d", $this->cid, $this->uid)->select();
		foreach ( $items as $v ) {
			$businessId = $v['business_id'];
			$productId = $v['product_id'];
			if ( !$cartItems[$productId] ) {
				$cartItems[$productId] = array(
						'productId' => $productId,
						'name' => $v['product_name'],
						'support_cod' => $v['support_cod'],
				);
			}
			$cartItems[$productId]['items'][$businessId] = array(
					'businessId' => $businessId,
					'productPrice' => $v['product_price'],
					'quantity' => $v['product_count'],
					'attrs' => toArray($v['product_attr']),
					'pic' => $v['product_pic'],
			        'goodsSnap' => $v['goods_snap'] ? unserialize($v['goods_snap']) : null,
			);
		}
		$this->items = $cartItems;
	}
	
	/**
	 * 添加商品
	 * @param map $item 商品数据(除product_goods表数据外新增如下)
	 *    array(
	 *      selectedAttributes => array(),
	 *      productPrice => 0.00,
	 *      businessId => '',
	 *    )
	 * @param int $quantity 数据
	 */
	public function addItem($item, $quantity) {
		$d = D("DistributionShopCart");
		$selectedAttributesString = arrayToString($item['selectedAttributes']);
		$d->where(array(
				'cid' => $this->cid,
				'uid' => $this->uid,
				'product_id' => $item['id'],
				'product_attr' => $selectedAttributesString,
		));
		$d0 = clone $d;
		$result = false;
		if( $productCartItem = $d->find() ) {
			$result = $d0->setField("product_count", $productCartItem['product_count'] + $quantity);
		} else {
			$result = $d->add(array(
					'cid' => $this->cid,
					'uid' => $this->uid,
					'business_id' => $this->getBusinessId($item['id']),
					'product_id' => $item['id'],
					'product_name' => $item['name'],
					'product_attr' => $selectedAttributesString,
					'product_pic' => $item['pic'],
					'product_count' => $quantity,
					'product_price' => $item['productPrice'],
					'support_cod' => $item['support_cod'],
			        'goods_snap' => serialize($item),
			));
		}
		if($result === false) return false;
		return true;
	}

	/**
	 * 从购物车中移除商品
	 * @param int $item_id 商品id
	 * @param string $businessId 业务id
	 */
	public function removeItem($item_id, $businessId) {
		if($this->uid) {
			if(false === M("DistributionShopCart")->where(array(
					'cid'=>$this->cid,
					'uid' => $this->uid,
					'product_id' => $item_id,
					'business_id' => $businessId,))->delete()) {
					return false;
			}
		}
		return true;
	}

	/**
	 * 更新商品
	 * @param int $item_id 商品id
	 * @param string $businessId 业务id
	 * @param map $updateItem 更新项   array('quantity'=>1)
	 */
	public function updateItem($item_id, $businessId, $updateItem) {
		if($this->uid) {
			$data = array();
			$config = array('quantity' => 'product_count'); // 可更新的字段配置
			foreach ($config as $k => $v) {
				key_exists($k, $updateItem) and $data[$v] = $updateItem[$k];
			}
			if(empty($data)) return false;
			if(false === M("DistributionShopCart")->where(array(
					'cid'=>$this->cid,
					'uid' => $this->uid,
					'product_id' => $item_id,
					'business_id' => $businessId,))->save($data)){
					return false;
			}
		}
		return true;
	}
	
	public function clearAll() {
		if($this->uid) {
			D("DistributionShopCart")->where("cid=%d and uid=%d", $this->cid, $this->uid)->delete();
		}
		$this->items = array();
	}

	/**
	 * 获得业务id
	 * @param unknown $item_id
	 * @return string
	 */
	public function getBusinessId($item_id) {
		return 'b'.session_id().$item_id.time().rand(0, 9).rand(0, 9);
	}

}